package cn.signalpha.common.aspect;

import cn.signalpha.common.annotation.OperateLogAnnotation;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.secure.utils.AuthUtil;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.utils.WebUtil;
import cn.signalpha.modules.system.entity.OperateLog;
import cn.signalpha.modules.system.service.IOperateLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * 表单重复提交AOP
 *
 * @author signalpha
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class OperateLogAspect {

	private final IOperateLogService operateLogService;

	/**
	 * 配置切入点
	 */
	@Pointcut("@annotation(cn.signalpha.common.annotation.OperateLogAnnotation)")
	public void operateLogPointCut() {}

	/**
	 * 处理完请求后执行此处代码
	 *
	 * @param joinPoint 切点
	 */
	@AfterReturning(pointcut = "@annotation(operateLogAnnotation)", returning = "jsonResult")
	public void doAfterReturning(JoinPoint joinPoint, OperateLogAnnotation operateLogAnnotation, Object jsonResult){
		HttpServletRequest request = WebUtil.getRequest();
		OperateLog operateLog = new OperateLog();
		operateLog.setRequestIp(WebUtil.getIP(request));
		operateLog.setRequestUrl(Objects.requireNonNull(request).getRequestURI());
		operateLog.setOperateType(operateLogAnnotation.operateType().getType());
		operateLog.setRequestParam(WebUtil.getRequestContent(request));
		operateLog.setResponseParam(JsonUtil.toJson(jsonResult));
		operateLog.setRemark(operateLogAnnotation.remark());
		operateLog.setCreateTime(new Date());

		//获取不到token用户则为授权模式
		TokenUser tokenUser = AuthUtil.getUser(request);
		if(tokenUser != null){
			operateLog.setTenantId(tokenUser.getTenantId());
			operateLog.setOperateId(tokenUser.getUserId());
			operateLog.setOperateName(tokenUser.getNickName());
			operateLog.setOperateAccount(tokenUser.getAccount());
		}
		operateLogService.save(operateLog);
	}

}
